package com.allenkerr;

import com.alibaba.fastjson.JSON;
import com.allenkerr.model.Person;
import com.google.gson.Gson;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 小柯 on 17/7/3.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoDbTest04 {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 存
     */
    @Test
    public void test1_0() {
        Map<String, Object> indexes = new LinkedHashMap<>();
        indexes.put("country", "China");
        indexes.put("city", "BeiJing");
        indexes.put("phone", 13522158746L);
        Person person = new Person("zhangSan", "123", "张三", indexes);
        mongoTemplate.insert(person);
    }

    @Test
    public void test1_1() throws URISyntaxException, IOException {
        URL url = this.getClass().getClassLoader().getResource("person.json");
        File file = new File(url.toURI());
        String json = FileUtils.readFileToString(file, Charset.forName("utf-8"));
        Gson gson = new Gson();
        Person p1 = gson.fromJson(json, Person.class);
//        Person p2 = JSON.parseObject(json, Person.class);
        mongoTemplate.insert(p1);
    }

    /**
     * 查
     */
    @Test
    public void test2() {
//        Query query = Query.query(Criteria.where("indexes.country").is("China"));
        Query query = Query.query(Criteria.where("indexes.countryId").is(23));
        List<Person> people = mongoTemplate.find(query, Person.class);
//        people.forEach(System.out::println);
        people.forEach(p -> System.out.println(JSON.toJSONString(p)));
    }

}
